package chapter2;

/**
 * @author ycj
 * @version 1.0
 * @description: TODO
 * @date 2022/5/16
 */

//模拟竞态
//解决的方案 nextId方法加上synchronized

public class Source2_2 {
    public static void main(String[] args) {
        //得到处理器数目
        int count=Runtime.getRuntime().availableProcessors();
        Thread[] threads = new Thread[count];
        for(int i=0;i<count;i++){
            threads[i]=new WorkTask(1);//每个线程处理5个请求
        }

        //尽量线程保证一起开始
        for (Thread thread : threads) {
            thread.start();
        }

        //Thread-8得到的requestId=abcdef9
        //Thread-3得到的requestId=abcdef4
        //Thread-2得到的requestId=abcdef3
        //Thread-7得到的requestId=abcdef8
        //Thread-6得到的requestId=abcdef7
        //Thread-4得到的requestId=abcdef5
        //Thread-0得到的requestId=abcdef3
        //Thread-5得到的requestId=abcdef6
        //Thread-1得到的requestId=abcdef3
        //Thread-9得到的requestId=abcdef10
        //Thread-10得到的requestId=abcdef11
        //Thread-11得到的requestId=abcdef12

        //有多个线程获取到了3
    }
}

class WorkTask extends Thread{
    private final int requestCount;
    private final Source2_1 source2_1=Source2_1.getRequestIdCreate();

    public WorkTask(int requestCount) {
        this.requestCount = requestCount;
    }

    @Override
    public void run() {
        int t=requestCount;
        while(t--!=0){
            String requestId = source2_1.nextId();
            try {
                //模拟线程处理业务
                Thread.sleep(80);
                System.out.println(Thread.currentThread().getName()+"得到的requestId="+requestId);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
